/**
 * 设备指纹收集和用户识别 - 前端示例代码
 */

class DeviceFingerprint {
    constructor() {
        this.apiBaseUrl = 'http://localhost:8080';
    }

    async collectDeviceInfo() {
        const deviceInfo = {
            deviceFingerprint: await this.generateDeviceFingerprint(),
            screenResolution: `${screen.width}x${screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            language: navigator.language || navigator.userLanguage,
            platform: navigator.platform
        };

        return deviceInfo;
    }

    async generateDeviceFingerprint() {
        const components = [];
        
        components.push(navigator.userAgent);
        components.push(navigator.language);
        components.push(navigator.platform);
        components.push(screen.width);
        components.push(screen.height);
        components.push(new Date().getTimezoneOffset());
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        ctx.textBaseline = 'top';
        ctx.font = '14px Arial';
        ctx.fillText('VR Exhibition Fingerprint', 2, 2);
        components.push(canvas.toDataURL());
        
        const fingerprint = await this.generateHash(components.join('|'));
        return fingerprint;
    }

    async generateHash(text) {
        const encoder = new TextEncoder();
        const data = encoder.encode(text);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
        return hashHex;
    }

    async identifyUser() {
        try {
            const deviceInfo = await this.collectDeviceInfo();
            
            const response = await fetch(`${this.apiBaseUrl}/anonymousUsers/identify`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(deviceInfo)
            });

            const result = await response.json();
            
            if (result.status === 200) {
                const userIdentity = result.data;
                localStorage.setItem('userToken', userIdentity.userToken);
                return userIdentity;
            } else {
                console.error('用户识别失败:', result.message);
                return null;
            }
        } catch (error) {
            console.error('设备识别请求失败:', error);
            return null;
        }
    }
}

// 页面加载时自动识别用户
document.addEventListener('DOMContentLoaded', async () => {
    const deviceFingerprint = new DeviceFingerprint();
    const userIdentity = await deviceFingerprint.identifyUser();
    
    if (userIdentity) {
        console.log('用户识别成功:', userIdentity.userToken);
        if (userIdentity.isNewUser) {
            console.log('欢迎新用户!');
        } else {
            console.log(`欢迎回来! 第${userIdentity.visitCount}次访问`);
        }
    }
}); 